<template>
  <div class="dynamic-table-container">
    <!-- 操作按钮区 -->
    <div class="table-operations mb-4">
      <a-button type="primary" @click="addRow"> <plus-outlined /> 新增 </a-button>

      <!-- 仅当有选中项时显示删除按钮 -->
      <a-button type="danger" @click="deleteSelectedRows" v-if="hasSelected" class="ml-2"> <delete-outlined /> 删除选中 </a-button>
    </div>

    <vxe-table
      border
      show-overflow
      keep-source
      height="300"
      ref="tableRef"
      :data="tableData"
      :edit-rules="validRules"
      :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }"
      @checkbox-all="selectAllChangeEvent"
      @checkbox-change="selectChangeEvent"
      id="id"
    >
      <vxe-column type="checkbox" width="60" fixed="left" />
      <vxe-column type="seq" width="70" fixed="left" />
      <vxe-column field="createor" title="创建人" fixed="left" :edit-render="{ name: 'AInput', defaultValue: '3232', placeholder: '请输入创建人' }" />
      <vxe-column field="projectManager" title="项目经理" fixed="left" :edit-render="{ placeholder: '请选择项目经理' }">
        <template #edit="{ row }">
          <!-- <JSelectUser v-model:value="row.projectManager" /> -->
          <a-input :value="row.projectManager" placeholder="请选择项目经理">
            <template #addonAfter>
              <div @click="openModalClick_User(row)">
                <MenuUnfoldOutlined />
              </div>
            </template>
          </a-input>
        </template>
        <!-- <template #default="{ row }">
          <span>{{ row.projectManager }}</span>
        </template> -->
      </vxe-column>
      <vxe-column field="dept" title="项目部门" fixed="left" :edit-render="{ placeholder: '请选择项目部门' }">
        <template #edit="{ row }">
          <!-- <JSelectDeptByByteluck v-model:value="row.dept" /> -->
          <!-- <JSelectDept v-model:value="row.dept" /> -->
          <a-input :value="row.dept" placeholder="请选择项目经理">
            <template #addonAfter>
              <div @click="openModalClick_Department(row)">
                <MenuUnfoldOutlined />
              </div>
            </template>
          </a-input>
        </template>
        <!-- <template #default="{ row }">
          <span>{{ row.dept }}</span>
        </template> -->
      </vxe-column>
      <vxe-column field="flowStatus" title="流程状态" :edit-render="{ name: 'AInput', placeholder: '请输入流程状态' }" />
      <vxe-column field="content" title="巡视内容" :edit-render="{ name: 'AInput', placeholder: '请输入巡视内容' }" />
      <vxe-column field="name" title="专业名称" :edit-render="{ name: 'AInput', placeholder: '请输入专业名称' }" />
      <vxe-column field="commander" title="专业负责人" :edit-render="{ name: 'AInput', placeholder: '请输入专业负责人' }" />
      <vxe-column field="startTime" title="巡视开始日期" :edit-render="{ name: 'ADatePicker', placeholder: '请选择巡视开始日期' }" />
      <vxe-column field="endTime" title="巡视结束日期" :edit-render="{ name: 'ADatePicker', placeholder: '请选择巡视结束日期' }" />
      <vxe-column field="status" title="状态" :edit-render="{ name: 'AInput', placeholder: '请输入状态' }" />
      <vxe-column field="sheet" title="巡视策划主表" :edit-render="{ name: 'AInput', placeholder: '请输入巡视策划主表' }" />
    </vxe-table>
    <DepartmentSelect ref="departmentSelectRef" @change="onChange_department" />
    <UserSelect ref="userSelectRef" @change="onChange_user" />
  </div>
</template>

<script setup lang="ts">
  import { ref, defineExpose, computed } from 'vue';
  import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import UserSelectModal from '/@/components/Form/src/cyj/components/modal/UserSelectModal.vue';
  import JSelectDeptByByteluck from '/@/components/Form/src/cyj/components/JSelectDeptByByteluck.vue';
  import { JSelectUser, JSelectDept } from '/@/components/Form';
  import { useModal } from '/@/components/Modal';
  import { MenuUnfoldOutlined } from '@ant-design/icons-vue';
  import RoleDrawer from '../../system/role/RoleDrawer.vue';
  import DepartmentSelect from '/@/components/Form/src/cyj/components/DepartmentSelectNative.vue';
  import UserSelect from '/@/components/Form/src/cyj/components/UserSelectNative.vue';

  const rowTmp: any = ref({});
  /**部门选择 */
  const departmentSelectRef = ref();
  const openModalClick_Department = (row) => {
    rowTmp.value = row;
    departmentSelectRef.value.openModalClick();
  };
  const onChange_department = (value, options) => {
    console.log('value, options', value, options);
    rowTmp.value.dept = options.map((item) => item.department_name);
  };

  /**人员选择 */
  const userSelectRef = ref();

  const openModalClick_User = (row) => {
    rowTmp.value = row;
    userSelectRef.value.openModalClick();
  };

  const onChange_user = (value, options) => {
    console.log('value, options', value, options);
    rowTmp.value.projectManager = options.map((item) => item.employee_name);
  };
  /**人员选择 */

  // 定义表格行数据类型
  interface TableRow {
    id: number;
    createor: string;
    flowStatus: string;
    content: string;
    name: string;
    commander: string;
    startTime: string;
    endTime: string;
    status: string;
    sheet: string;
  }

  const validRules = ref({
    createor: [{ required: true, message: '必须填写' }],
    flowStatus: [{ required: true, message: '必须填写' }],
    content: [{ required: true, message: '必须填写' }],
    name: [{ required: true, message: '必须填写' }],
    commander: [{ required: true, message: '必须填写' }],
    startTime: [{ required: true, message: '必须填写' }],
    endTime: [{ required: true, message: '必须填写' }],
    status: [{ required: true, message: '必须填写' }],
    sheet: [{ required: true, message: '必须填写' }],
  });

  // 表格数据源
  const tableData = ref<TableRow[]>([]);

  // 选中的行ID
  type Key = string | number;
  const selectedRowKeys = ref<Key[]>([]);
  const tableRef = ref();
  // 处理选择变化
  const selectAllChangeEvent = () => {
    const $table = tableRef.value;
    if ($table) {
      const records = $table.getCheckboxRecords();
      console.log('records-----', records);
      selectedRowKeys.value = records.map((item) => item.id);
    }
  };

  const selectChangeEvent = () => {
    const $table = tableRef.value;
    if ($table) {
      const records = $table.getCheckboxRecords();
      console.log('records-----', records);
      selectedRowKeys.value = records.map((item) => item.id);
    }
  };

  const hasSelected = computed(() => selectedRowKeys.value.length > 0);

  // 新增行
  const addRow = () => {
    const newId = Math.max(...tableData.value.map((row) => row.id), 0) + 1;
    tableData.value.push({
      id: newId,
      createor: '',
      flowStatus: '',
      content: '',
      name: '',
      commander: '',
      startTime: '',
      endTime: '',
      status: '',
      sheet: '',
    });
  };

  // 删除选中行
  const deleteSelectedRows = () => {
    tableData.value = tableData.value.filter((row) => !selectedRowKeys.value.includes(row.id));
    selectedRowKeys.value = [];
  };

  const onReset = () => {
    tableData.value = [];
  };

  const validateAll = async () => {
    const $table = tableRef.value;
    if ($table) {
      try {
        const res = await $table.validate(true);
        console.log('res-----res----res', res);
        if (res) {
          return Promise.reject(false); // 校验失败
        } else {
          return Promise.resolve(true); // 校验通过
        }
      } catch (error) {
        return Promise.reject(false); // 校验失败
      }
    }
  };

  // 暴露给父组件的属性和方法
  defineExpose({
    validateAll,
    // 暴露表格数据
    tableData,
    // 可选：暴露新增行方法
    addRow,
    // 可选：暴露删除选中行方法
    deleteSelectedRows,
    onReset,
  });
</script>

<style scoped>
  .dynamic-table-container {
    /* padding: 20px; */
  }

  .table-operations {
    display: flex;
    align-items: center;
  }

  .error-message {
    color: #ff4d4f;
    font-size: 12px;
    margin-top: 4px;
    height: 16px;
  }
</style>
